<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>红绿灯倒计时</title>
		<link rel="stylesheet" href="red.css" />
	</head>
	<body>
		<div class="box">
			<!--红灯-->
			<div id="r"></div>
			<!--黄灯-->
			<div id="y"></div>
			<!--绿灯-->
			<div id="g"></div>
			<!--倒计时-->
			<div id="count" class="count"></div>
		</div>
		<script>
		
			var lamp={
				red:{
					obj:document.getElementById('r'),
					time:30,
					next:'green',
					style:['red','gray','gray']
				},
				yellow:{
					obj:document.getElementById('y'),
					time:5,
					next:'red',
					style:['gray','yellow','gray']
				},
				green:{
					obj:document.getElementById('g'),
					time:35,
					next:'yellow',
					style:['gray','gray','green']
				},
				change:function(style){
					this.red.obj.style.background=style[0];
					this.yellow.obj.style.background=style[1];
					this.green.obj.style.background=style[2];
					
				}
			};
			//创建倒计时对象；显示倒计时（两位数）
			var count={
				obj:document.getElementById('count'),
				change:function(num){
					this.obj.innerHTML=(num<10?'0'+num:num);
				}
			};
			//2、静态：设置红绿灯亮是初始化页面（3个灯背景颜色、数字）
			/*1)获取当前绿灯的相关数据，2、设置剩余时间 3、设置背景颜色*/
			var now=lamp.green;
			var t=now.time;
			count.change(now.time);
			lamp.change(now.style);	/* 1、设置红黄绿灯、倒计时对象
			   2、设置绿灯亮时初始化页面
			   3、实现红绿灯倒计时*/
				setInterval(myfun,1000);
				function myfun(){
					if(t--<=0){
						now=lamp[now.next];
						t=now.time;
						lamp.change(now.style);
					}
					count.change(t)
				}
		</script>		
	</body>
</html>
